package com.shqcjd.sinopecdemomobile.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.RouteListBean;
import com.shqcjd.sinopecdemomobile.model.pojo.RouteQueryBean;
import com.shqcjd.sinopecdemomobile.ui.adapter.InspectionAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.RouteSpinnerAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.PrefUtils;
import com.shqcjd.sinopecdemomobile.util.WrapContentLinearLayoutManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class InspectionActivity extends BaseActivity {

    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.ll_inspection_select)
    LinearLayout llInspectionSelect;
    @BindView(R.id.rl_inspection_search)
    RelativeLayout rlInspectionSearch;
    @BindView(R.id.rv_inspection)
    RecyclerView rvInspection;
    @BindView(R.id.sr_inspection)
    SwipeRefreshLayout srInspection;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.et_inspection_search)
    EditText etInspectionSearch;
    @BindView(R.id.rl_pop)
    RelativeLayout rlPop;


    private Context context;
    private String area = "";//片区
    private String branch_factory = "";//分厂
    private String factory = "";//厂
    private String group = "";//集团编号

    private int total;
    private InspectionAdapter inspectionAdapter;
    private List<RouteListBean.ItemsBean> adapterList = new ArrayList<>();
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多
    private String strSearch = "";
    private View contentView;


    private RouteSpinnerAdapter locationAdapter;//片区适配器
    private RouteSpinnerAdapter companyAdapter;//集团适配器
    private RouteSpinnerAdapter factoryAdapter;//工厂适配器
    private RouteSpinnerAdapter childAdapter;//分厂适配器
    private List<RouteQueryBean> locationList = new ArrayList<>();
    private List<RouteQueryBean> childList = new ArrayList<>();
    private List<RouteQueryBean> companyList = new ArrayList<>();
    private List<RouteQueryBean> factoryList = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_inspection;
    }

    @Override
    public void init() {
        super.init();
        context = this;
    }

    @Override
    public void initView() {
        super.initView();
        tvIncludeTitle.setText("线路列表");
        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        llInspectionSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(rlPop);
            }
        });

        etInspectionSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                strSearch = s.toString();
                refreshData();
            }
        });

        srInspection.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        getQueryLocationBean("area");
        refreshData();
    }

    private void refreshData() {
        refreshOrLoadMore();
        srInspection.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        adapterList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore() {
        if (inspectionAdapter != null) {
            inspectionAdapter.notifyLoadMoreToLoading();
        }
    }

    private void getData(int p) {
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p + "");
        map.put("pageSize", Config.PAGE_TOTAL + "");
        map.put("area", area);
        map.put("branch_factory", branch_factory);
        map.put("factory", factory);
        map.put("group", group);
        map.put("patrol_root_name", strSearch);
        map.put("user_id", PrefUtils.getInt(context, PrefUtils.USER_ID, 0)+"");

        ApiService.routeListHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<RouteListBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
//                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<RouteListBean> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            total = retData.data.total;
                            adapterList.addAll(retData.data.items);
                            if (inspectionAdapter == null) {
                                rvInspection.setLayoutManager(new WrapContentLinearLayoutManager(context));
                                inspectionAdapter = new InspectionAdapter(adapterList, context);
                                rvInspection.setAdapter(inspectionAdapter);

                                inspectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        Intent it = new Intent(context, RouteInfoActivity.class);
                                        it.putExtra("rId", adapterList.get(position).id);
                                        startActivity(it);

                                    }
                                });

                                inspectionAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                                    @Override
                                    public void onLoadMoreRequested() {
                                        int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                                        if (page >= pageSize) {
                                            rvInspection.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    inspectionAdapter.loadMoreEnd();
                                                }
                                            });
                                        } else {
                                            loadMoreData();
                                        }
                                    }
                                });
                            }
                            if (isRefreshOrLoadMore == 1) {
                                page = page + 1;
                                inspectionAdapter.loadMoreComplete();
                            }
                            if(adapterList.size()==0){
                                rlIsnull.setVisibility(View.VISIBLE);
                            }else{
                                rlIsnull.setVisibility(View.INVISIBLE);
                            }
                            inspectionAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srInspection.setRefreshing(false);
                    }
                });
    }

    private void showPopupWindow(ViewGroup view) {
        if(contentView!=null){
            contentView.setVisibility(View.VISIBLE);
            return;
        }
        contentView = LayoutInflater.from(context).inflate(
                R.layout.pop_window, view, false);
        view.addView(contentView);

        RelativeLayout rl = contentView.findViewById(R.id.rl);
        LinearLayout ll_pop_content = contentView.findViewById(R.id.ll_pop_content);
        Spinner sp_pop_location = contentView.findViewById(R.id.sp_pop_location);
        Spinner sp_pop_child = contentView.findViewById(R.id.sp_pop_child);
        Spinner sp_pop_company = contentView.findViewById(R.id.sp_pop_company);
        Spinner sp_pop_factory = contentView.findViewById(R.id.sp_pop_factory);
        Button btn_pop_reset = contentView.findViewById(R.id.btn_pop_reset);
        Button btn_pop_commit = contentView.findViewById(R.id.btn_pop_commit);

        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentView.setVisibility(View.GONE);
            }
        });
        ll_pop_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //重置
        btn_pop_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sp_pop_location.setSelection(0);
            }
        });

        //确定
        btn_pop_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                area = locationList.size()>0?locationList.get(sp_pop_location.getSelectedItemPosition()).code:"";
                group = companyList.size()>0?companyList.get(sp_pop_company.getSelectedItemPosition()).code:"";
                factory = factoryList.size()>0?factoryList.get(sp_pop_factory.getSelectedItemPosition()).code:"";
                branch_factory = childList.size()>0?childList.get(sp_pop_child.getSelectedItemPosition()).code:"";
                refreshData();
                contentView.setVisibility(View.GONE);
            }
        });


        sp_pop_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryCompanynBean(locationList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_company.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryFactoryBean(companyList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_factory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryChildBean(factoryList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_child.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        locationAdapter = new RouteSpinnerAdapter(context, locationList);
        childAdapter = new RouteSpinnerAdapter(context, childList);
        companyAdapter = new RouteSpinnerAdapter(context, companyList);
        factoryAdapter = new RouteSpinnerAdapter(context, factoryList);
        sp_pop_location.setAdapter(locationAdapter);
        sp_pop_company.setAdapter(companyAdapter);
        sp_pop_factory.setAdapter(factoryAdapter);
        sp_pop_child.setAdapter(childAdapter);
    }

    private void getQueryLocationBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            locationList.clear();
                            companyList.clear();
                            factoryList.clear();
                            childList.clear();
                            locationList.addAll(retData.data);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryCompanynBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            companyList.clear();
                            factoryList.clear();
                            childList.clear();
                            companyList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryFactoryBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            factoryList.clear();
                            childList.clear();
                            factoryList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryChildBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            childList.clear();
                            childList.add(new RouteQueryBean("", "", "全部"));
                            childList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

}